import 'dart:ffi';

import 'package:bot_toast/bot_toast.dart';
// import 'package:euromillions/tools/EJ_ballsView.dart';
// import 'package:euromillions/tools/EJ_config.dart';
// import 'package:euromillions/tools/EJ_emsBalls.dart';
// import 'package:euromillions/tools/models/EJ_DataViewModels.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';
// import 'package:kerala_lottery/tools/models/KL_keralaLottoDataModel.dart';

import '../tools/KaL_Config.dart';
import '../tools/FL_CustomLoading.dart';
import '../tools/FL_Switch.dart';
import '../tools/FL_emsBalls.dart';
import '../tools/KaL_drawNumbersView.dart';
import '../tools/models/KL_keralaLottoDataModel.dart';
import '../tools/models/KL_keralaLottoModel.dart';
import '../tools/models/KaL_DataViewModels.dart';
import '../tools/models/KaL_LottoModel.dart';
// import 'package:normal_lotto/tools/NL_lottoInfoModel.dart';

// import '../tools/NL_CustomLoading.dart';
// import '../tools/NL_Switch.dart';
// import '../tools/NL_config.dart';
// import '../tools/NL_viewModel.dart';

class EJ_checkerDetailPageVC extends StatefulWidget {
  EJ_checkerDetailPageVC({super.key, required this.myTicketNumbers});
  List myTicketNumbers;
  @override
  State<EJ_checkerDetailPageVC> createState() => _EJ_checkerDetailPageVCState();
}

class _EJ_checkerDetailPageVCState extends State<EJ_checkerDetailPageVC> {
  var _ticketNumbers = [];
  late var _lottoModels = [];
  late var NL_Moldes = [];
  bool _isShowWin = false; //是否显示中间的结果

  late var _winningNumbers = [];
  late var _allNumbers = [];

  var _numbersMap = {};

  void showWinningNumbers() {
    if (_isShowWin) {
      _lottoModels = _winningNumbers;
    } else {
      _lottoModels = _allNumbers;
    }

    setState(() {});
  }

  void configData() {
    // BotToast.showCustomLoading(toastBuilder: (cancelFunc) {
    //   return FLCustomLoading();
    // });
    List _allDataModels = KL_keralaLottoDataModel().allDataModels;
    debugPrint('checkerDatas---$_allDataModels');

    ///
    List<String> numbersList = [];
    // numbersList = _ticketNumbers.map((item) => item?.toString() ?? '').toList();
    for (Map element in _ticketNumbers) {
      var tNum = element['number'];
      numbersList.add(tNum);
    }

    for (KL_keralaLottoModel lModel in _allDataModels) {
      //名字
      var gameName = lModel.game_name;
      var drawCode = lModel.draw_code;
      var _title = '$gameName($drawCode)';

      //时间
      var draw_datetime_utc = lModel.draw_datetime_utc;
      DateTime drawDateTime = DateTime.parse(draw_datetime_utc + '+0000');
      var _dateTimeString = DateFormat('dd/MMM/yyyy').format(drawDateTime);

      // PrizeModel prizeModel = lModel.prizes![0];
      // List ticketNumbers = prizeModel.ticket_numbers!;
      List prizes = lModel.prizes ?? [];
      if (prizes.isNotEmpty) {
        for (var i = 0; i < prizes.length; i++) {
          PrizeModel pModel = prizes[i];
          List ticketNumbers = pModel.ticket_numbers!;
          if (ticketNumbers.isNotEmpty) {
            for (String element in ticketNumbers) {
              // 使用正则表达式去掉多余字符
              String cleaned = element.replaceAll(RegExp(r'[^a-zA-Z0-9]'), '');
              List<String> tNumberList = cleaned.split('');

              bool winning = compearMatchingElements(numbersList, tNumberList);
              //取每期第一中奖
              if (i == 0) {
                List nums = [];
                for (var j = tNumberList.length - 1; j >= 0; j--) {
                  String tNum = tNumberList[j];
                  bool isRight = false;

                  if (winning) {
                    int numbersLength = numbersList.length;
                    int mostSimilarLength = tNumberList.length;
                    int idx = j - (mostSimilarLength - numbersLength);
                    if (idx >= 0) {
                      String rNum = numbersList[idx];
                      if (tNum == rNum) {
                        isRight = true;
                      }
                    }
                  }

                  var num = {
                    'number': tNum,
                    'isRight': isRight,
                    'isNormal': false
                  };
                  nums.add(num);
                }
                var prizeAmount = pModel.prize_amount;
                var prize = pModel.rank_title;
                var title = 'Matched $prize Prize';
                if (i == 0) {
                  title = '$prize Prize';
                }
                var numbersMap = {
                  'title': title,
                  'balls': nums.reversed.toList()
                };

                ///
                var cellDataMap = {
                  'title': _title,
                  'dateTime': _dateTimeString,
                  'numbersMap': numbersMap,
                  'amount': prizeAmount + ' INR',
                  'winning': winning
                };
                _allNumbers.add(cellDataMap);
                if (winning) {
                  _winningNumbers.add(cellDataMap);
                }
              } else {
                //展出中奖号码
                if (winning && i != 0) {
                  // _winningNumbers.add(value)
                  List nums = [];
                  for (var j = tNumberList.length - 1; j >= 0; j--) {
                    String tNum = tNumberList[j];
                    bool isRight = false;

                    int numbersLength = numbersList.length;
                    int mostSimilarLength = tNumberList.length;
                    int idx = j - (mostSimilarLength - numbersLength);
                    if (idx >= mostSimilarLength) {
                      String rNum = numbersList[idx];
                      if (tNum == rNum) {
                        isRight = true;
                      }
                    }
                    var num = {
                      'number': tNum,
                      'isRight': isRight,
                      'isNormal': false
                    };
                    nums.add(num);
                  }
                  var prizeAmount = pModel.prize_amount;
                  var prize = pModel.rank_title;
                  var title = 'Matched $prize Prize';
                  if (i == 0) {
                    title = '$prize Prize';
                  }
                  var numbersMap = {
                    'title': title,
                    'balls': nums.reversed.toList()
                  };

                  ///
                  var cellDataMap = {
                    'title': _title,
                    'dateTime': _dateTimeString,
                    'numbersMap': numbersMap,
                    'amount': prizeAmount + ' INR',
                    'winning': winning
                  };
                  _winningNumbers.add(cellDataMap);
                  _allNumbers.add(cellDataMap);
                }
              }
            }
          }
        }
      }
    }
    debugPrint('_allNumbers---$_allNumbers');
    setState(() {
      _lottoModels = _allNumbers;
    });
  }

  bool compearMatchingElements(
      List<String> currentArray, List<String> subArray) {
    bool count = false;

    ///
    String cArr = currentArray.join('');
    String sArr = subArray.join('');
    if (right(cArr, sArr.length) == sArr) {
      count = true;
    }

    return count;
  }

  String right(String str, int length) {
    return str.substring(str.length - length);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    ///
    // NL_Moldes = KaL_DataViewModels().EJ_models.reversed.toList();
    // _ticketNumbers = widget.myTicketNumbers;
    for (var element in widget.myTicketNumbers) {
      _ticketNumbers.add(element);
    }
    _numbersMap = {'title': '', 'balls': _ticketNumbers};
    debugPrint('$_ticketNumbers');
    // _getConfigData();
    configData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          'All Draws Checker',
          style: TextStyle(
            fontWeight: FontWeight.w600,
            fontSize: 18,
          ),
        ),
        backgroundColor: Colors.white,
        foregroundColor: KaL_Config.KaL_MainColor,
        centerTitle: true,
      ),
      body: Container(
        color: KaL_Config.KaL_pageBgColor,
        child: Column(
          children: [
            headerView(),
            contentListView(),
          ],
        ),
      ),
    );
  }

  Widget contentListView() {
    return Expanded(
      child: ListView.builder(
          padding: const EdgeInsets.all(15),
          itemCount: _lottoModels.length,
          // itemCount: 2,
          itemBuilder: (BuildContext context, int index) {
            var model = _lottoModels[index];

            return listCell(model);
          }),
    );
  }

  Widget listCell(Map model) {
    var _title = model['title'];
    var _dateTime = model['dateTime'];
    bool winning = model['winning'];
    var amount = winning ? model['amount'] : '';
    var numbersMap = model['numbersMap'];

    return Container(
      padding: const EdgeInsets.only(top: 7.5, bottom: 7.5),
      height: 140,
      child: GestureDetector(
        onTap: () {
          debugPrint('result');
          // _goToDetailPage(nums.reversed.toList());
        },
        child: Container(
          // margin: const EdgeInsets.fromLTRB(10, 7.5, 10, 7.5),
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
          ),
          child: Column(children: [
            Container(
              margin: const EdgeInsets.only(left: 10, right: 10),
              // height: 40,
              // color: Colors.yellow,
              child: Row(children: [
                Container(
                  margin: EdgeInsets.only(left: 5, top: 5),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(_title,
                          style: TextStyle(
                            fontWeight: FontWeight.w700,
                            fontSize: 14,
                            color: HexColor('#d32f7d'),
                          )),
                      Text(_dateTime,
                          style: TextStyle(
                            fontWeight: FontWeight.w600,
                            fontSize: 11,
                            color: HexColor('#999999'),
                          )),
                    ],
                  ),
                ),
                const Spacer(),
                Text(
                  amount,
                  style: TextStyle(
                      fontWeight: FontWeight.w700,
                      fontSize: 15,
                      color: HexColor('#D32F7D')),
                ),
              ]),
            ),
            Expanded(
                child: Container(
              width: double.infinity,
              child: Row(
                children: [
                  Expanded(
                      child: Container(
                    // color: Colors.red,
                    alignment: Alignment.centerLeft,
                    child: KalDrawnumbersview(data: numbersMap),
                  )),
                  // assetTagView(),
                ],
              ),
            )),
          ]),
        ),
      ),
    );
  }

  Widget assetTagView() {
    return Container(
      alignment: Alignment.center,
      height: double.infinity,
      width: 30,
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(10),
            bottomRight: Radius.circular(10),
          )),
      child: Image.asset(
        'assets/sys_imgs/EJ_union.png',
        width: 8.0,
        height: 13.0,
      ),
    );
  }

  Widget contentListCell(var model) {
    KaL_LottoModel lModel = model;
    bool isWin = false;
    //balls
    List<Widget> balls = [];
    int regularRightCount = 0;
    for (var i = 0; i < lModel.regularnumbers!.length; i++) {
      var num = lModel.regularnumbers![i];
      bool isRightNum = false;
      //
      for (var element in _ticketNumbers) {
        bool isRegular = element['isRegular'];
        if (isRegular) {
          var rightNum = element['number'];
          if (num == rightNum) {
            isRightNum = true;
            regularRightCount += 1;
          }
        }
      }
      // for (var i = 0; i < _ticketNumbers.length - 1; i++) {
      //   var element = _ticketNumbers[i];
      //   // var ticketNum = element['num'];
      //   if (num == element) {
      //     isRightNum = true;
      //     regularRightCount += 1;
      //   }
      // }
      balls
          .add(ball('$num', true, isRightNumber: isRightNum, isMyTicket: true));
    }

    int extranRightCount = 0;
    for (var i = 0; i < lModel.extranumbers!.length; i++) {
      var num = lModel.extranumbers![i];
      bool isRightNum = false;
      //
      // var element = _ticketNumbers.last;
      // // var ticketNum = element['num'];
      // if (num == element) {
      //   isRightNum = true;
      //   extranRightCount += 1;
      // }
      for (var element in _ticketNumbers) {
        bool isRegular = element['isRegular'];
        if (!isRegular) {
          var rightNum = element['number'];
          if (num == rightNum) {
            isRightNum = true;
            extranRightCount += 1;
          }
        }
      }

      balls.add(
          ball('$num', false, isRightNumber: isRightNum, isMyTicket: true));
    }

    for (var i = 0; i < lModel.bonusnumbers!.length; i++) {
      var num = lModel.bonusnumbers![i];
      bool isRightNum = false;

      for (var element in _ticketNumbers) {
        bool isRegular = element['isRegular'];
        if (!isRegular) {
          var rightNum = element['number'];
          if (num == rightNum) {
            isRightNum = true;
            extranRightCount += 1;
          }
        }
      }

      balls.add(
          ball('$num', false, isRightNumber: isRightNum, isMyTicket: true));
    }

    //payout
    var payoutString = '\$0.0';
    var payouttable = lModel.payouttable;
    var matchedStr = "$regularRightCount + $extranRightCount";
    for (PayoutModel pModel in payouttable!) {
      var matched = pModel.matched;
      if (matched == matchedStr) {
        // payoutString = pModel.payout;
        if (pModel.payout != null) {
          payoutString = pModel.payout;
        } else {
          var sortorder = pModel.sortorder;
          payoutString = 'Prize $sortorder';
        }
        isWin = true;
      }
    }

    //date
    var dayStr = lModel.drawtime;
    DateTime date = DateTime.parse(dayStr!);
    String dayOfWeek = DateFormat('MMM').format(date);
    String dayOfMonth = DateFormat('dd').format(date);
    String dayOfYear = DateFormat('yyyy').format(date);
    var dateStr = '$dayOfMonth/$dayOfWeek/$dayOfYear';

    return Container(
      margin: const EdgeInsets.only(bottom: 15),
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.all(Radius.circular(10.0))),
      child: Column(
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const SizedBox(width: 15),
                Text(
                  dateStr,
                  style: const TextStyle(
                    fontSize: 13,
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                  ),
                ),
                const Spacer(),
                isWin
                    ? Text(
                        payoutString,
                        style: TextStyle(
                          fontSize: 15,
                          fontWeight: FontWeight.w600,
                          // color: KaL_Config.AL_themeColor_HL,
                          color: Colors.red,
                        ),
                      )
                    : Container(),
                const SizedBox(width: 15),
              ],
            ),
          ),
          Container(
            // color: Colors.red,
            padding: const EdgeInsets.fromLTRB(20, 10, 20, 10),
            child: Wrap(
              alignment: WrapAlignment.center,
              spacing: 3.0,
              children: balls,
            ),
          ),
        ],
      ),
    );
  }

  Widget headerView() {
    // List<Widget> balls = [];
    // for (var i = 0; i < _ticketNumbers.length; i++) {
    //   var ballMap = _ticketNumbers[i];
    //   var num = ballMap['num'];
    //   bool isRegular = ballMap['isRegular'];
    //   balls.add(ball(num, isRegular));
    // }
    return Container(
      height: 110,
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.2), // 阴影颜色
            spreadRadius: 1, // 扩散半径
            blurRadius: 10, // 模糊半径
            offset: Offset(0, 1), // 阴影偏移
          ),
        ],
      ),
      child: Column(
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: [
                const SizedBox(width: 20),
                const Text(
                  'My Ticket',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.w600,
                    color: Colors.black,
                  ),
                ),
                const Spacer(),
                const Text(
                  'Show Winning Only',
                  style: TextStyle(
                    fontWeight: FontWeight.w400,
                    fontSize: 11,
                    color: Colors.black,
                  ),
                ),
                FLSwitch(
                  isOpen: _isShowWin,
                  onPressed: (p0) {
                    debugPrint('-----$p0');
                    _isShowWin = p0;
                    showWinningNumbers();
                  },
                ),
                const SizedBox(width: 15),
              ],
            ),
          ),
          Expanded(
              child: Container(
            child: KalDrawnumbersview(data: _numbersMap),
          ))
        ],
      ),
    );
  }

  //
  Widget ball(
    String num,
    bool isRegular, {
    bool isRightNumber = false,
    bool isMyTicket = false,
  } //是否是选中的号码
      ) {
    double viewW = 38.0;
    double margin = 3;
    double radius = (viewW - margin) * 0.5;
    Color bgColor =
        isRegular ? KaL_Config.KaL_MainColor : KaL_Config.KaL_extramNumColor;

    Color textColor = Colors.white;
    Color borderColor = HexColor('#aaaaaa');
    //
    if (isMyTicket) {
      Color bgGrayColor = isRegular ? HexColor('#aaaaaa') : HexColor('666666');
      bgColor = isRightNumber ? bgColor : bgGrayColor;
      textColor = isRightNumber ? Colors.white : textColor;
      borderColor = isRightNumber ? KaL_Config.KaL_MainColor : bgGrayColor;
    }

    // var extramNumImg = 'assets/systems_Imgs/extramNum_Star_gray.png';
    if (!isRegular && isRightNumber) {
      textColor = KaL_Config.KaL_extramNumTitleColor;
      borderColor = borderColor;
      // extramNumImg = 'assets/systems_Imgs/extramNum_Star.png';
      // viewW = 42.0;
      // radius = 0.0;
    }

    double padding = 0;
    //星星不需要圆角
    // if (!isRegular) {
    //   viewW = 42.0;
    //   radius = 0.0;
    //   padding = 3.0;
    // }

    return SizedBox(
      width: viewW,
      height: viewW,
      child: Container(
        alignment: Alignment.center,
        margin: EdgeInsets.all(margin),
        decoration: BoxDecoration(
          color: bgColor,
          // color: Colors.green,
          borderRadius: BorderRadius.all(Radius.circular(radius)),
          border: Border.all(width: 2, color: borderColor),
          // image: !isRegular
          //     ? DecorationImage(
          //         image: AssetImage(extramNumImg), // 替换为您的图片路径
          //         fit: BoxFit.cover, // 图片填充方式
          //       )
          //     : null,
        ),
        child: Padding(
          padding: EdgeInsets.only(top: padding),
          child: Text(
            num,
            style: TextStyle(
              color: textColor,
              fontWeight: FontWeight.w600,
              fontSize: 14,
            ),
          ),
        ),
      ),
    );
  }
}
